package com.flushbonading.controller;

import com.flushbonading.annotation.BackStage;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author zyx 2134208960@qq.com
 * @date 2021/5/19 16:32
 * @since 1.0.0
 */
@RestController
@Api(tags = "文件上传测试")
@BackStage
@RequestMapping("/file")
public class TestUploadController {
    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/upload")
    public void postData(MultipartFile file) throws IOException {
        String url = "http://10.168.200.61:8090/api/img/upload";
        MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
        bodyMap.add("file", new FileSystemResource(convert(file)));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyMap, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(url,
                HttpMethod.POST, requestEntity, String.class);
    }
    public static File convert(MultipartFile file)
    {
        File convFile = new File("temp_image", file.getOriginalFilename());
        if (!convFile.getParentFile().exists()) {
            System.out.println("mkdir:" + convFile.getParentFile().mkdirs());
        }
        try {
            convFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(convFile);
            fos.write(file.getBytes());
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return convFile;
    }
}
